<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="用户名" prop="userId">
        <el-select
          v-model="queryParams.userId"
          placeholder="请选择用户"
          style="width: 240px"
        >
          <el-option
            v-for="item in userList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['orders:orders:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['orders:orders:export']"
          >导出</el-button
        >
      </el-col> -->
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="ordersList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单ID" align="center" prop="orderId" />
      <el-table-column label="用户名" align="center" prop="userId">
        <template #default="scope">
          {{ findUserById(scope.row.userId) }}
        </template>
      </el-table-column>
      <el-table-column label="总价格" align="center" prop="totalPrice" />
      <el-table-column label="订单状态" align="center" prop="progress" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            :disabled="scope.row.progress != '已申请理赔'"
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            >理赔</el-button
          >
          <!-- <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['orders:orders:remove']"
            >删除</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="ordersRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="是否理赔" prop="status">
          <el-select
            v-model="form.status"
            placeholder="请选择订单状态"
            style="width: 240px"
          >
            <el-option key="1" label="同意" value="1" />
            <el-option key="0" label="不同意" value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Orders">
import {
  listOrders,
  getOrders,
  delOrders,
  addOrders,
  updateOrders,
} from "@/api/orders/orders";
import { listUser } from "@/api/system/user";
const { proxy } = getCurrentInstance();
import { addComment, listComment } from "@/api/comment/comment";

const ordersList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10000,
    userId: null,
    totalPrice: null,
    status: null,
  },
  rules: {
    totalPrice: [
      { required: true, message: "总价格不能为空", trigger: "blur" },
    ],
    status: [
      { required: true, message: "订单状态不能为空", trigger: "change" },
    ],
  },
});

const userList = ref([]);

const { queryParams, form, rules } = toRefs(data);

//获取用户列表
const getUserList = () => {
  listUser().then((response) => {
    userList.value = response.rows.filter((v) => v.roleIds[0] === 2);
  });
};

// 根据id查询用户
const findUserById = (id) => {
  const current = userList.value.filter((v) => v.userId === id)[0];
  return current.userName;
};

getUserList();

/** 查询订单管理列表 */
const getList = async () => {
  loading.value = true;
  const response = await listOrders(queryParams.value);
  const reseponse2 = await listComment();
  console.log(333, reseponse2);

  response.rows.map((item1) => {
    reseponse2.rows.map((item2) => {
      if (item2.orderId == item1.orderId) {
        item1.comment = item2.contant;
      } else {
        item1.comment = "";
      }
    });
  });
  response.rows.forEach((v) => {
    if (v.status == 0 && v.comment.length == 0) {
      v.progress = "已投保";
    } else if (v.status == 0 && v.comment.length != 0) {
      v.progress = "已申请理赔";
    } else if (v.status == 1) {
      v.progress = "已理赔";
    }
  });
  ordersList.value = response.rows;
  total.value = response.total;
  loading.value = false;
};

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    orderId: null,
    userId: null,
    totalPrice: null,
    status: null,
    createdAt: null,
    updatedAt: null,
  };
  proxy.resetForm("ordersRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.orderId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加订单管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _orderId = row.orderId || ids.value;
  getOrders(_orderId).then((response) => {
    form.value = response.data;
    form.value.status = response.data.status.toString();
    open.value = true;
    title.value = "修改订单管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["ordersRef"].validate((valid) => {
    if (valid) {
      if (form.value.orderId != null) {
        updateOrders(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addOrders(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _orderIds = row.orderId || ids.value;
  proxy.$modal
    .confirm('是否确认删除订单编号为"' + _orderIds + '"的数据项？')
    .then(function () {
      return delOrders(_orderIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

getList();
</script>
